import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow
from MainWindow import Ui_MainWindow
from douyin_download import DouyinDownload


class DownloadThread(QThread):
    finished = pyqtSignal(str)

    def __init__(self, target):
        super().__init__()
        self.target = target

    def run(self):
        self.target()
        self.finished.emit("下载完成")


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.download)
        self.douyin_download = DouyinDownload()
        self.menu_action.triggered.connect(self.on_click_help)
        self.msgBox.finished.connect(lambda x: self.lineEdit.setText(''))


    def on_click_help(self):
        self.help_info.exec()

    def download(self):
        share_link_desc = self.lineEdit.text()
        if len(share_link_desc) == 0:
            return
        self.douyin_download.share_link_desc = share_link_desc
        print('download...')
        self.thread = DownloadThread(target=self._download)
        self.thread.finished.connect(self.completed)
        self.thread.start()
        self.progressbar.setVisible(True)
        self.download_text.setVisible(True)


    def _download(self):
        self.douyin_download.download_share()

    def completed(self, result):
        print(result)
        self.progressbar.setVisible(False)
        self.download_text.setVisible(False)
        if not self.douyin_download.filenames:
            download_text = '视频或者图文不存在'
        else:
            download_text = f'文件保存至{self.douyin_download.filenames[0]}：\n'
            for i in range(1, len(self.douyin_download.filenames)):
                download_text += f'{self.douyin_download.filenames[i]}  下载完成\n'
        self.msgBox.setText(download_text)
        self.msgBox.exec()


def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()
